package com.tsing.common.utils;

import com.tsing.common.exceptions.BusinessException;
import com.tsing.common.exceptions.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Util {

    private final static Logger logger = LoggerFactory.getLogger(Base64Util.class);

    public static String encode(byte[] b) {
        if (b != null) {
            String result = Base64.getEncoder().encodeToString(b);
            return result;
        }
        throw new BusinessException(CommonException.Proxy.BASE64_PARAM_IS_REQUIRED);
    }

    public static String encode(String src) {
        if (!StringUtils.isBlank(src)) {
            return encode(src.getBytes());
        }
        throw new BusinessException(CommonException.Proxy.BASE64_PARAM_IS_REQUIRED);
    }

    public static byte[] decode(String s) {
        byte[] result = Base64.getDecoder().decode(s);
        return result;
    }

    public static String decodeStr(String s) {
        byte[] b = decode(s);
        try {
            return b != null ? (new String(b, "UTF-8")) : null;
        } catch (UnsupportedEncodingException e) {
            logger.error("base解密报错{}", e.getMessage());
            throw new BusinessException(CommonException.Proxy.BASE64_ENCODING_ERROR);
        }
    }

}
